# -*- coding:utf-8 -*-

from Queen.config.mission_config import svip_mission_dict, main_mission_dict, test_mission_dict, web_mission_dict
from Queen.config.queen_config import zookeeper_host, queen_election_path, zookeeper_session_timeout, queen_identifier
from Queen.zookeeper.zookeeper_controller import ZKController
from logger_config import logger_factory
from Queen.dispatch.mission_dispatch import dispatch_mission
from time import sleep

logger = logger_factory()


def queen_loop():
    """
    Queen节点循环访问mission_dict中的内容，读取任务信息并分配
    :return:
    """
    logger.info('start to dispatch missions')
    while True:
        for key in main_mission_dict.keys():
            try:
                dispatch_mission(key, main_mission_dict)
            except Exception as e:
                logger.error(e)
                logger.error(f'Error happened at mission {key}')
                continue
            # sleep(180)
            sleep(10)


def main():
    while True:
        try:
            zk_controller = ZKController(zk_hosts=zookeeper_host, election_path=queen_election_path,
                                         session_timeout=zookeeper_session_timeout, identifier=queen_identifier)
            zk_controller.start()
            zk_controller.run_func(queen_loop)
        except Exception as e:
            print(e)
            logger.error(e)
            sleep(10)


if __name__ == '__main__':
    main()